package com.originskyseed.platform.user.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.common.annotation.SysLog;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.core.util.bean.ExportExcelUtil;
import com.originskyseed.platform.user.i18n.UserResponseMsg;
import com.originskyseed.platform.user.model.ChannelSub;
import com.originskyseed.platform.user.model.PlayerRelateRewardApply;
import com.originskyseed.platform.user.model.PlayerRelateRewardReview;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IChannelSubService;
import com.originskyseed.platform.user.service.IPlayerRelateRewardApplyService;
import com.originskyseed.platform.user.service.IPlayerRelateRewardReviewService;
import com.originskyseed.platform.user.vo.request.PlayerRelateRewardApplyRequestVO;
import com.originskyseed.platform.user.vo.request.PlayerRelateRewardReviewRequestVO;

/**
 * 玩家奖励申请审核表Controller类（OSI_PLAYER_RELATE_REWARD_REVIEW）
 *
 * @author wlj
 */
@Controller
@RequestMapping("/playerRelateRewardReview")
@BaseLocaleResource(localeFileName = "i18n_user")
public class PlayerRelateRewardReviewController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(PlayerRelateRewardReviewController.class);

	@DubboReference
	private IPlayerRelateRewardReviewService playerRelateRewardReviewService;

	@DubboReference
	private IPlayerRelateRewardApplyService playerRelateRewardApplyService;

	@DubboReference
	private IChannelSubService channelSubService;

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/playerRelateRewardReviewList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<PlayerRelateRewardReview>> playerRelateRewardReviewList(HttpServletRequest request) {
		BaseResponseBody<BasePage<PlayerRelateRewardReview>> result = null;
		try {
			// 请求对象
			PlayerRelateRewardReviewRequestVO requestVO = this.getParameterBean(PlayerRelateRewardReviewRequestVO.class);

			// 分页查询
			BasePage<PlayerRelateRewardReview> page = new BasePage<PlayerRelateRewardReview>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.playerRelateRewardReviewService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<PlayerRelateRewardReview>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<PlayerRelateRewardReview>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 奖励申请审核_分页查询-公会
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/playerRelateRewardCheckList.json")
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<PlayerRelateRewardApply>> playerRelateRewardCheckList(HttpServletRequest request) {
		BaseResponseBody<BasePage<PlayerRelateRewardApply>> result = null;
		try {
			// 请求对象
			PlayerRelateRewardApplyRequestVO requestVO = this.getParameterBean(PlayerRelateRewardApplyRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if (userInfo.getSourceSys() == 0 && (userInfo.getType() == 2 || userInfo.getType() == 5)) { // ow 运管
				BasePage<PlayerRelateRewardApply> page = new BasePage<PlayerRelateRewardApply>(requestVO.getPageNo(), requestVO.getPageSize());
				page = this.playerRelateRewardApplyService.selectCheckListByPage(requestVO.toMap(), page);
				result = new BaseResponseBody<BasePage<PlayerRelateRewardApply>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<PlayerRelateRewardApply>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 奖励申请审核列表导出Excel模板
	 * 
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@GetMapping("/playerRelateRewardCheckToExcelModel.json")
	@SysLog(module = "直播管理类模块", operationDesc = "奖励申请审核列表导出Excel模板")
	public void playerRelateRewardCheckToExcelModel(HttpServletRequest request, HttpServletResponse response) {
		try {
			// excel标题
			String[] title = { "用户ID*", "奖励类型*", "奖励奖品*", "申请时间*", "备注信息*", "所属子渠道*", "所属子渠道账号*", "申请人*", "审核状态*", "审核时间*", "操作人*" };
			// excel文件名
			String fileName = "奖励申请审核信息导出模板.xls";
			// sheet名
			String sheetName = "奖励申请审核信息模板";
			String[][] values = new String[0][];
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 奖励发放申请审核列表导出Excel
	 * 
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/playerRelateRewardCheckToExcel.json")
	@SysLog(module = "直播管理类模块", operationDesc = "奖励申请审核信息导出Excel")
	public void playerRelateRewardCheckToExcel(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 请求对象
			PlayerRelateRewardApplyRequestVO requestVO = this.getParameterBean(PlayerRelateRewardApplyRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			SimpleDateFormat RechargeTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			List<PlayerRelateRewardApply> list = null;
			// OW 运管
			if (userInfo.getSourceSys() == 0 && (userInfo.getType() == 2 || userInfo.getType() == 5)) {
				list = this.playerRelateRewardApplyService.selectCheckListToExcel(requestVO.toMap());
			}
			// excel标题
			String[] title = { "用户ID", "奖励类型", "奖励奖品", "申请时间", "备注信息", "所属子渠道", "所属子渠道账号", "申请人", "审核状态", "审核时间", "操作人" };
			// excel文件名
			String fileName = "奖励申请审核信息.xls";
			// sheet名
			String sheetName = "奖励申请审核信息";
			String[][] values = new String[list.size()][];

			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					values[i] = new String[title.length];
					PlayerRelateRewardApply obj = list.get(i);
					values[i][0] = obj.getPlayerId();
					if (obj.getType() != null) {
						if (obj.getType() == 1) {
							values[i][1] = "充值累积奖励";
						}
						if (obj.getType() == 2) {
							values[i][1] = "开通贵族奖励";
						}
						if (obj.getType() == 3) {
							values[i][1] = "登录奖励";
						}
					} else {
						values[i][1] = "";
					}
					values[i][2] = "奖励奖品待确定";
					values[i][3] = RechargeTime.format(obj.getApplyTime());
					values[i][4] = obj.getRemark() == null ? "" : obj.getRemark();
					values[i][5] = obj.getChannelSubName() == null ? "" : obj.getChannelSubName();
					values[i][6] = obj.getChannelSubAccount() == null ? "" : obj.getChannelSubAccount();
					values[i][7] = obj.getApplyName();
					if (obj.getReviewStatus() != null) {
						if (obj.getReviewStatus() == 0) {
							values[i][8] = "待审核";
						}
						if (obj.getReviewStatus() == 1) {
							values[i][8] = "审核不通过";
						}
						if (obj.getReviewStatus() == 2) {
							values[i][8] = "审核通过";
						}
					} else {
						values[i][8] = "";
					}
					values[i][9] = obj.getReviewTime() == null ? "" : RechargeTime.format(obj.getReviewTime());
					values[i][10] = obj.getReviewName() == null ? "" : obj.getReviewName();
				}
			}
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 输出Excel
	 *
	 * @param response
	 * @param title
	 * @param fileName
	 * @param sheetName
	 * @param values
	 * @throws IOException
	 */
	private void outPutExcel(HttpServletResponse response, String[] title, String fileName, String sheetName, String[][] values) throws IOException {
		// 创建HSSFWorkbook
		HSSFWorkbook wb = ExportExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
		// 将文件存到指定位置
		this.setResponseHeader(response, fileName);
		OutputStream os = response.getOutputStream();
		wb.write(os);
		os.flush();
		os.close();
	}

	/**
	 * 发送响应流方法
	 *
	 * @param response
	 * @param fileName
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.error(e.getMessage(), e);
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage(), ex);
		}
	}

	/**
	 * 申请详情
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/playerRelateRewardParticularsAndCheckById.json")
	@RequiredParams(names = { "id" }) // 奖励申请ID
	public BaseResponseBody playerRelateRewardParticularsAndCheckById(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			String id = this.getParameterString("id", null);
			Map<String, Object> resultMap = new HashMap<>();
			PlayerRelateRewardApply playerRelateRewardApply = this.playerRelateRewardApplyService.selectByPrimaryKey(id);
			ChannelSub channelSub = this.channelSubService.selectByChannelSubId(playerRelateRewardApply.getChannelSubId());

			// 申请奖励的对象信息
			resultMap.put("playerRelateRewardApply", playerRelateRewardApply);
			// 子渠道名称
			resultMap.put("channelSubName", channelSub.getName());

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.SELECT_DATA_SUCCESS.getMsg()), resultMap);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.SELECT_DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 开放平台_申请奖励审核_保存信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/playerRelateRewardReviewSave.json")
	@RequiredParams(names = { "rewardApplyId", "reviewStatus" })
	public BaseResponseBody playerRelateRewardReviewSave(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			PlayerRelateRewardReview playerRelateRewardReview = this.getParameterBean(PlayerRelateRewardReview.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if (StringUtils.isNotBlank(playerRelateRewardReview.getRewardApplyId()) && playerRelateRewardReview.getReviewStatus() != null) { // 申请奖励ID
				PlayerRelateRewardReview rewardReview = this.playerRelateRewardReviewService.selectByRewardApplyId(playerRelateRewardReview.getRewardApplyId());
				if (StringUtils.isNotBlank(rewardReview.getId())) {
					playerRelateRewardReview.setId(rewardReview.getId());
					playerRelateRewardReview.setReviewTime(new Date());
					playerRelateRewardReview.setReviewName(userInfo.getName());
					playerRelateRewardReview.setReviewId(userInfo.getId());
					this.playerRelateRewardReviewService.updateByPrimaryKey(playerRelateRewardReview);
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.PLAYER_RELATE_REWARD_REVIEW_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.PLAYER_RELATE_REWARD_REVIEW_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/playerRelateRewardReviewDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> playerRelateRewardReviewDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.playerRelateRewardReviewService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

}
